package com.gagakuai.bpm.service.scheduleTask;

import com.gagakuai.bpm.dao.mapper.scheduleTask.UserInfoMapper;
import com.gagakuai.bpm.domian.dto.response.ResponseStatusDto;
import com.gagakuai.bpm.domian.dto.scheduleTask.BPMUserVo;
import com.gagakuai.bpm.domian.dto.scheduleTask.Group;
import com.gagakuai.bpm.domian.dto.scheduleTask.User;
import com.gagakuai.bpm.domian.dto.scheduleTask.UserOfGroup;
import com.gagakuai.bpm.rpcservice.openfeign.UserHttpApi;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;

@Slf4j
@Service
public class Task implements Runnable{

    private final UserHttpApi userHttpApi;
    private final UserInfoMapper userInfoMapper;
    private final int MAX_INSERT_COUNT = 100;

    public Task(UserHttpApi userHttpApi, UserInfoMapper userInfoMapper){
        this.userHttpApi = userHttpApi;
        this.userInfoMapper = userInfoMapper;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void run() {
        ResponseStatusDto<List<BPMUserVo>> responseStatusDto = userHttpApi.getSystemUserInfoList();
        if(responseStatusDto == null){
            return;
        }

        int STATUS_CODE = 200;
        if(!String.valueOf(STATUS_CODE).equals(responseStatusDto.getCode())){
            log.info("数据同步失败,原因为：{}",  responseStatusDto.getMessage());
            return;
        }
        if(ObjectUtils.isEmpty(responseStatusDto.getData())){
            log.info("数据为空");
            return;
        }

       log.info("==================开始定时任务======================");
       log.info("接收到的数据为：{}", responseStatusDto.getData());

        userInfoMapper.deleteUserOfGroup();
        userInfoMapper.deleteGroup();
        userInfoMapper.deleteUser();

        List<Group> groupList = new ArrayList<>();
        List<User> userList = new ArrayList<>();
        List<UserOfGroup> userOfGroupList = new ArrayList<>();
        HashMap containsUser = new HashMap<>();
        HashMap containsGroup = new HashMap<>();
        HashMap containsShip = new HashMap<>();

        responseStatusDto.getData().forEach( item ->{
            int count = Math.max(groupList.size(), Math.max(userList.size(), userOfGroupList.size()));
            if(count >= MAX_INSERT_COUNT){
                int _count_user = userInfoMapper.batchUser(userList);
                int _count_group = userInfoMapper.batchGroup(groupList);
                int _count_userOfGroup = userInfoMapper.batchUserOfGroup(userOfGroupList);

                if(Math.min(_count_user, Math.min(_count_group, _count_userOfGroup)) > 0){
                    userList.clear();
                    groupList.clear();
                    userOfGroupList.clear();
                }
            }
            String userId = String.valueOf(item.getUserId());
            String username = item.getUsername();

            if(!containsUser.containsKey(userId)){
                User user = new User();
                user.setId(userId);
                user.setName(username);
                userList.add(user);
                containsUser.put(userId, null);
            }

            item.getDeptInfo().forEach(it ->{
                String deptId = String.valueOf(it.getDeptId());
                String deptName = it.getName();
                boolean main = it.getMain();

                if(main && !containsGroup.containsKey(deptId)){
                    Group group = new Group();
                    group.setDeptId(deptId);
                    group.setName(deptName);
                    groupList.add(group);
                    containsGroup.put(deptId, null);
                }

                if(!containsShip.containsKey(userId + deptId)){
                    UserOfGroup userOfGroup = new UserOfGroup();
                    userOfGroup.setUserId(userId);
                    userOfGroup.setGroupId(deptId);
                    userOfGroupList.add(userOfGroup);
                    containsShip.put(userId + deptId, null);
                }
            });
        });

        if(userList.size() > 0){
            userInfoMapper.batchUser(userList);
        }

        if(groupList.size() > 0){
            userInfoMapper.batchGroup(groupList);
        }

        if(userOfGroupList.size() > 0){
            userInfoMapper.batchUserOfGroup(userOfGroupList);
        }

        log.info("==================结束定时任务======================");
    }

    public static void main(String... args){
        ObjectMapper objectMapper = new ObjectMapper();
        String url = "http://10.123.171.127:8083/ca/user/v2/getUserInfo";
        try {
            LinkedHashMap obj = objectMapper.readValue(new URL(url),
                    new TypeReference<LinkedHashMap>() {
                    });
            List<Object> bpmUserVoList = (List<Object>) obj.get("data");
            System.out.println(obj.get("code").toString());
            LinkedHashMap linkedHashMap = (LinkedHashMap) bpmUserVoList.get(0);
            BPMUserVo bpmUserVo = new BPMUserVo();
            bpmUserVo.setUserId(Long.parseLong(linkedHashMap.get("userId").toString()));
            System.out.println(bpmUserVo.getUserId() + "");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
